import { isEmpty } from 'loadsh'
import { defineStore } from 'pinia'
import router from '../router'
// Create a new store instance.
const useRouterStore = defineStore('routerStore', {
  // other options...
  state: () => {
    return {
      breadcrumbList: [
        {
          path: '/dashboard',
          name: '首页',
          fix: true,
          index: 0,
        },
      ],
      activeIndex: 0,
    }
  },
  actions: {
    addBreadcrumb(route) {
      for (const key in this.breadcrumbList) {
        if (
          this.breadcrumbList[key].path === route.path ||
          this.breadcrumbList[key].name === route.name
        ) {
          this.breadcrumbList[key].params = !isEmpty(route.params)
            ? route.params
            : this.breadcrumbList[key].params
          this.breadcrumbList[key].query = !isEmpty(route.query)
            ? route.query
            : this.breadcrumbList[key].query
          return
        }
      }
      route.index = this.breadcrumbList.length

      this.activeIndex = route.index
      this.breadcrumbList.push(route)
    },
    removeBreadcrumb(item) {
      if (this.activeIndex !== item.index) {
        if (item.index < this.activeIndex) {
          this.activeIndex -= 1
        }
      } else {
        this.activeIndex = item.index - 1 > -1 ? item.index - 1 : 0
      }
      this.breadcrumbList.splice(item.index, 1)
      this.breadcrumbList.forEach((item, index) => {
        item.index = index
      })
      return this.breadcrumbList[this.activeIndex] || {}
    },
    addBreadcrumbByPush(route) {
      this.addBreadcrumb(route)
      console.log(route, 888)
      router.push(route.path)
    },
  },
  getters: {},
  // 是否开启数据持久化
  persist: false,
})

export default useRouterStore
